package com.itheima.servlet;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

public class ServletConfigDemo extends HttpServlet {

    // 1. 定义一个ServletConfig类型的成员变量
    private ServletConfig servletConfig;

    @Override
    public void init(ServletConfig config) throws ServletException {
        // 2. 在init方法中, 将ServletConfig类型的参数赋值给成员变量
        this.servletConfig = config;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("ServletConfigDemo");
        // 3. 在Servlet中, 通过成员变量获取ServletConfig对象 根绝key获取value
        System.out.println(servletConfig.getInitParameter("username"));
        System.out.println(servletConfig.getInitParameter("password"));

        // 4. 获取所有的key
        Enumeration<String> enumeration = servletConfig.getInitParameterNames();
        while (enumeration.hasMoreElements()) {
            String key = enumeration.nextElement();
            String value = servletConfig.getInitParameter(key);
            System.out.println(key + " = " + value);
        }
        // 5. 获取servlet的名称
        String servletName = servletConfig.getServletName();
        System.out.println(servletName);

        // 6. 获取ServletContext对象
        ServletContext servletContext = servletConfig.getServletContext();
        System.out.println(servletContext);

        // 7. 获取共享数据
        Object name = servletContext.getAttribute("name");
        System.out.println(name);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
